$(function () {
    // 切换登录注册tab
    $('#login').on('click', '.tab', function () {
        console.log(this.dataset.tabCon);
        $('#login .form-info').hide()
        $(`#login .${this.dataset.tabCon}`).show();
        $(this).addClass('active').siblings().removeClass('active')
    })
    // 滚动跟随
    $(window).on("load", function () {
        $(window).on("scroll", function () {
            var scrollTop = $(this).scrollTop();
            $("#login").stop().animate({
                top: scrollTop
            })
        })
    })

    $('#login .close_btn').click(function () {
        $('#login').hide();
        $('#popup').hide();
    })
    $('.login-link').click(function () {
        $('#login').show();
        $('#popup').show();
        $('#login .denglu').click();
    })
    $('.register-link').click(function () {
        $('#login').show();
        $('#popup').show();
        $('#login .zhuce').click();
    })
})


$(function () {
    // 登录提交
    $('#login_submit').click(function () {
        if (!gdyz) {}
        let oForm = $('#login_form')[0];
        let user = {
            name: oForm.name.value,
            pwd: oForm.pwd.value,
        }
        $.ajax({
            type: "get",
            url: "/login",
            data: user,
        }).done(function (res) {
            if (res.code == 200) {
                if (oForm.remem.checked) {
                    Cookies.set('recent', JSON.stringify(user))
                } else {
                    Cookies.remove('recent');
                }

                sessionStorage.setItem('uname', user.name);
                sessionStorage.setItem('uid', res.data.uid);

                location.reload();
            }
        });
        return false;
    })
    // 注册正则
    class YZ {
        constructor(selector, reg, {
            wrong,
            empty,
            isAllowEmpty = false
        }) {
            this.el = $(selector)[0];
            this.reg = reg;
            this.wrong = wrong;
            this.oTip = $(this.el).siblings('.error_tip');
            this.oTrue = $(this.el).siblings('.status')
            this.empty = empty;
            this.mouseHandler();
            this.isAllowEmpty = isAllowEmpty;
        }
        test() {
            if (this.el.type == 'checkbox') {
                return this.reg.test(this.el.checked);
            }
            return this.reg.test(this.el.value);
        }
        true() {
            $(this.oTrue).show();
            $(this.oTip).hide();
        }
        wrongTip() {
            if (this.el.value == "") {
                if (this.empty) {
                    $(this.oTip).text(this.empty);
                }
                if (this.isAllowEmpty) {
                    return;
                }
                $(this.oTip).text(this.wrong);
            } else {
                $(this.oTip).text(this.wrong);
            }
            $(this.oTrue).hide();
            $(this.oTip).show();
        }
        mouseHandler() {
            $(this.el).change(() => {
                if (this.test()) {
                    this.true();
                } else {
                    this.wrongTip();
                }
            })
        }
    }
    class MyReg {
        constructor(cmp) {
            this.cmp = cmp;
        }
        test(value) {
            return this.cmp(value);
        }
    }
    let mobileYZ = new YZ('#register_form [name="mobile"]', /^\d{11}$/, {
        wrong: "请输入正确的手机号码",
        empty: "手机号不能为空",
    });
    $('#register_form [name="mobile"]').change(function() {
        yzm = undefined;
    })
    let emailYZ = new YZ('#register_form [name="email"]', new MyReg((value) => {
        return /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(value) || value == "";
    }), {
        wrong: "请输入正确的邮箱号",
        isAllowEmpty: true,
    });
    let pwdYZ = new YZ('#register_form [name="pwd"]', /^(?=.*[a-zA-Z])(?=.*\d)[^]{8,40}$/, {
        wrong: "请输入由8-40个字符组成，须含字母和数字的密码",
    });
    let cpwdYZ = new YZ('#register_form [name="cpwd"]', new MyReg((value) => {
        return $('#register_form [name="pwd"]').val() == value && value != "";
    }), {
        wrong: "再次输入密码",
        empty: "再次输入密码"
    });
    let otpCodeYZ = new YZ('#register_form [name="otpCode"]', new MyReg((value) => {
        return yzm && yzm == value
    }), {
        wrong: "验证码错误",
        empty: "请输入验证码"
    });
    let agree_policyYZ = new YZ('#register_form [name="agree_policy"]', new MyReg((value) => {
        return value
    }), {
        wrong: "请同意用户协议",
    });
    let YZs = [mobileYZ, emailYZ, pwdYZ, cpwdYZ, otpCodeYZ,agree_policyYZ];

    // 滑动验证
    let gdyz = false;
    $(function () {
        var SlideVerifyPlug = window.slideVerifyPlug;
        var slideVerify = new SlideVerifyPlug('#verify-wrap', {
            wrapWidth: '316', //设置 容器的宽度 ,不设置的话，会设置成100%，需要自己在外层包层div,设置宽度，这是为了适应方便点；
            initText: '请按住滑块，拖动到最右边', //设置  初始的 显示文字
            sucessText: '验证通过', //设置 验证通过 显示的文字
            getSuccessState: function (res) {
                //当验证完成的时候 会 返回 res 值 true，只留了这个应该够用了 
                console.log(res);
                gdyz = res;
                if (slideVerify.slideFinishState) {
                    $('.value').html(slideVerify.slideFinishState)
                    $('#resetBtn').removeClass('prohibit')
                }
            }
        });
    })
    let yzm;
    let timer;
    $('#login .huoqu1 .hqyz').click(function () {
        if (!mobileYZ.test()) {
            return false;
        }
        if (gdyz == false) {
            $('#login .bangding .error_tip').text('请拖动上方滑块再获取验证码').show();
            return false;
        }
        yzm = parseInt(Math.random() * 10 ** 6);
        console.log("短信验证码:", yzm);
        $('#login .huoqu2 .hqyz span').text(120)
        $('#login .huoqu2').show();
        let seconds = 120;
        timer = setInterval(function () {
            if (seconds <= 0) {
                $('#login .huoqu2').hide();
                clearInterval(timer)
            }
            seconds--;
            $('#login .huoqu2 .hqyz span').text(seconds)
        }, 1000)
    })

    // 注册提交
    $('#register_submit').click(function () {
        let res = YZs.reduce((result, item) => {
            if (!item.test()) {
                item.wrongTip && item.wrongTip();
                return false;
            }
            return result;
        }, true)
        if (!res) {
            return false;
        }

        let oForm = $('#register_form')[0];
        let user = {
            name: oForm.mobile.value,
            pwd: oForm.pwd.value,
            mobile: oForm.mobile.value,
            email: oForm.email.value,
        }

        $.ajax({
            url: "/regphone",
            type: "post",
            data: user,
        }).then( (res) => {
            var {
                msg,
                code,
            } = res;
            if (code == 200) {
                $.ajax({
                    type: "post",
                    url: "/register",
                    data: user,
                }).done(function (msg) {
                    if (code == 200) {
                        alert('注册成功')
                        $('#login_form [name="name"]').val(user.name)
                        $('#login .tab.denglu').click()
                        Cookies.remove('recent');
                        $('#login_form')[0].remem.checked = false;
                    } else {
                        alert('注册失败')
                    }
                });
            } else {
                $('#register_form [name="mobile"]').siblings('.status').hide();
                $('#register_form [name="mobile"]').siblings('.error_tip').text('手机号已被注册')
                $('#register_form [name="mobile"]').siblings('.error_tip').show()

                //重置验证码
                $('#login .huoqu2').hide();
                clearInterval(timer)
            }
        })

        return false;
    })

    // 登出
    $('#myLoginStatus .login-out').click(function () {
        sessionStorage.removeItem('uname');
        sessionStorage.removeItem('uid')
        location.reload();
    })

    // 载入保存的用户
    $(document).ready(function () {
        let user = JSON.parse(Cookies.get('recent') || null);
        if (user) {
            let oForm = $('#login_form')[0];
            oForm.name.value = user.name;
            oForm.pwd.value = user.pwd;
            oForm.remem.checked = true;
        }
    })

    // 载入已登录用户名
    $(document).ready(function () {
        let uname = sessionStorage.uname;
        if (uname) {
            $('#myLoginWrap').hide();
            $('#myLoginStatus .login-user').text(uname)
            $('#myLoginStatus').show();
            $('#statusbar .unlogin').hide();
            $('#statusbar .name').text(uname)
            $('#statusbar .name').show();
        }
    })
})